package cn.youyeku.zsxh.api;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.youyeku.zsxh.Utils.LogUtils;
import okhttp3.Cookie;

/**
 * Created by youye on 17-3-27.
 */

public class myCookies {
//    private String name;
//    private String value;
//    private long expiresAt;
//    private String domain;
//    private String path;
//    private boolean secure;
//    private boolean httpOnly;
//    private boolean persistent; // True if 'expires' or 'max-age' is present.
//    private boolean hostOnly; // True unless 'domain' is present.


    public static String toJson(List<Cookie> cookies) throws JSONException {


        JSONArray jsonArray = new JSONArray();
        for (Cookie cookie : cookies) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", cookie.name());
            jsonObject.put("value", cookie.value());
            jsonObject.put("expiresAt", cookie.expiresAt());
            jsonObject.put("domain", cookie.domain());
            jsonObject.put("path", cookie.path());
            jsonObject.put("httpOnly", cookie.httpOnly());
            jsonObject.put("persistent", cookie.persistent());
            jsonObject.put("hostOnly", cookie.hostOnly());
            jsonObject.put("secure", cookie.secure());
            jsonArray.put(jsonObject);

        }
//        LogUtils.w("==="+jsonArray.toString());
        return jsonArray.toString();
    }

    public static List<Cookie> toCoookies(String data) throws JSONException {


        JSONArray jsonArray = new JSONArray(data);
        List<Cookie> cookies = new ArrayList<>();
        int arr_len = jsonArray.length();
        for (int i = 0; i < arr_len; i++) {
            JSONObject object = jsonArray.getJSONObject(i);

            Cookie.Builder builder = new Cookie.Builder();
            builder.name(object.getString("name"));
            builder.value(object.getString("value"));
            builder.expiresAt(object.getLong("expiresAt"));
            builder.domain(object.getString("domain"));
            builder.path(object.getString("path"));
            builder.secure();
            builder.httpOnly();
            builder.httpOnly();
            cookies.add(builder.build());
        }

        return cookies;
    }

    /**
     * cookies 序列化成 string
     *
     * @param cookie 要序列化的cookie
     * @return 序列化之后的string
     */
    protected String encodeCookie(SerializableOkHttpCookies cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {

            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * 将字符串反序列化成cookies
     *
     * @param cookieString cookies string
     * @return cookie object
     */
    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
        } catch (IOException e) {

        } catch (ClassNotFoundException e) {

        }

        return cookie;
    }

    /**
     * 二进制数组转十六进制字符串
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * 十六进制字符串转二进制数组
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

}
